import axios from 'axios'
import { ElMessage } from 'element-plus'
import { errMessage } from './status'
import { getToken } from './cookieUtil'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const req = axios.create({
    baseURL: '/api',
    timeout: 60000
})

// 请求封装
req.interceptors.request.use((config) => {
    const hasToken = (config.headers || {}).hasToken === false
    if (getToken() && !hasToken) config.headers['Authorization'] = getToken()
    return config
}, err => {
    Promise.reject(err)
})

// 响应封装
req.interceptors.response.use((res) => {
    const code = res.data.code
    const msg = res.data.msg

    if (code !== 200) {
        if (msg) ElMessage.error(msg)
        else ElMessage.error(errMessage(code))
        return Promise.reject(errMessage(code))
    } else return res.data

}, err => {
    let {
        message
    } = err;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage.error(message)
    return Promise.reject(err)
})

export default req;